<?php
/**
 * User: onwer
 * Date: 11-11-1
 * Time: 下午11:24
 */


class DB{
    public $pdo;
    protected $table_type;
    public $errorinfo=array();
    public  $tablename;
    public function __construct($tablename){
        try {
            $PDO = new PDO(DBDSN, DBUSER, DBPASSWORD);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
       $PDO->query('set names utf8');
       $this->pdo=$PDO;
       $this->table_type=array('f_system_','f_user_');
       $this->tablename=$tablename;
    }
    /**
     * @param array $param array('name'=>'aaa')
     * @param string $tablename ''
     * @return int
     */
    public function insert($param,$tablename=''){
        $tablename=$tablename===''?$this->tablename:$tablename;
        $filed = 'id';
        $value = 'NULL';
        foreach ($param as $k => $v) {
            $v = $this->safefilter($v);
            $filed .= sprintf(' ,`%s`', $k);
            $value .= sprintf(' , %s', $v);
        }

        $sql=sprintf('INSERT INTO %s (%s) VALUES (%s)',$tablename,$filed,$value);
        $r = $this->pdo->exec($sql);
        $this->errorinfo = $this->pdo->errorInfo();
        return $r!==false;
    }
    /**
     * @param  string $condition  id=5
     * @param string $tablename ''
     * @return int
     */
    public function delete($condition,$tablename=''){
        $tablename=$tablename===''?$this->tablename:$tablename;
        $sql= sprintf('DELETE FROM %s WHERE %s',$tablename,$condition);
        $r = $this->pdo->exec($sql);
        $this->errorinfo = $this->pdo->errorInfo();
        return $r!==false;
    }
    /**
     * @param array $param array('name'=>'222')
     * @param string $condition id=2
     * @param string $tablename ''
     * @return int
     */
    public function update($param,$condition,$tablename=''){
        $tablename=$tablename===''?$this->tablename:$tablename;
        $str='';
        foreach ($param as $key=>$val) {
            $val = $this->safefilter($val);
            $str.=$key.' = '.$val.',';
        }
        $str=substr($str,0,-1);
        $sql= sprintf('UPDATE %s SET %s WHERE %s',$tablename,$str,$condition);
        $r = $this->pdo->exec($sql);
        $this->errorinfo = $this->pdo->errorInfo();
        return $r!==false;
    }
    /**
     * @param string $condition id=2
     * @param string $limit 0,10
     * @param string $filed *
     * @param string $tablename ''
     * @return array
     */
    public function select($condition='',$limit='',$filed='*',$tablename=''){
        if($condition!==''){
            $condition=' WHERE '.$condition;
        }
        $tablename=$tablename===''?$this->tablename:$tablename;
        $sql=sprintf('SELECT %s  FROM  `%s` %s %s',$filed,$tablename,$condition,$limit);
        $sth = $this->pdo->query($sql);
        if($sth){
            $r = $sth->fetchAll(PDO::FETCH_ASSOC);
            $this->errorinfo = $sth->errorInfo();;
        }else{
            $r=array();
        }

        return $r;
    }
    public function query($sql){
        $sth=$this->pdo->query($sql);
        if($sth){
            $r = $sth->fetchAll(PDO::FETCH_ASSOC);
            $this->errorinfo = $sth->errorInfo();;
        }else{
            $r=array();
        }

        return $r;
    }
    /**
     * @param $sql
     * @return bool
     */
    public function exec($sql){
        $r=$this->pdo->exec($sql);
        $this->errorinfo=$this->pdo->errorInfo();
        return $r!==false;
    }
    /**
     * @param  string $str
     * @return int 0失败，1成功
     */
    public function isletter($str){
        return preg_match('/^[a-z]+$/i',$str);
    }
    /**
     * 是否有效的名称，英文开头，可以有字符串
     * @param string $str
     * @return int 0失败，1成功
     */
    public function isvalid($str){
        return preg_match('/^[a-z][a-z_]*$/i',$str);
    }
    /**
     * @description 添加单引号，并过滤单引号
     * @param  string $str
     * @return bool
     */
    public function safefilter($str){
        //$str = htmlentities($str,ENT_QUOTES,'utf-8');
        //script|i?frame|style|html|body|title|link|meta
        $str = preg_replace('/href=["|\']?javascript/','href=',$str);
        $str = preg_replace('/(<[^>]*?)on[a-z]+=\'=.*?\'/i','$1',$str);
        $str = preg_replace('/(<\/?)(script|i?frame|html|title|meta|link|style|body)(.*?)>/i','&lt;$2&gt;',$str);
        $str = str_replace("'",'\\\'',$str);
        return "'$str'" ;
        //return $this->pdo->quote($str,PDO::PARAM_STR);
    }
    /**
     * 结束事物
     * 参数，每一个sql结果。
     * @return bool
     */
    protected function endTranst(){
        $isok=array_walk(func_get_args(),create_function('$arg','return $arg===true;'));
        if($isok){
            $this->pdo->commit();
            return true;
        }else{
            $this->pdo->rollBack();
            return false;
        }
    }
}